<template>
  <div class="left-panel" :class="{ collapsed: isCollapsed }">
    <div class="toggle-button" @click="togglePanel">
      <span v-if="isCollapsed">▶</span>
      <span v-else>◀</span>
    </div>
    <div class="panel-content" v-show="!isCollapsed">
      <h3>绘制工具</h3>
      <div class="draw-controls">
        <button
            @click="startDrawing"
            :disabled="isDrawing"
            class="draw-button"
        >
          {{ isDrawing ? '绘制中...' : '开始绘制区域' }}
        </button>
        <button
            @click="stopDrawing"
            :disabled="!isDrawing"
            class="stop-button"
        >
          结束绘制
        </button>
        <button
            @click="clearAllAreas"
            :disabled="Object.keys(polygonAreas).length === 0"
            class="clear-button"
        >
          全部清除
        </button>
      </div>

      <div v-if="Object.keys(polygonAreas).length > 0" class="area-list">
        <h4>已绘制区域：</h4>
        <div
            v-for="(coords, name) in polygonAreas"
            :key="name"
            class="area-item"
        >
          <span class="area-name" @click="focusArea(name)" style="flex-grow: 1;">{{ name }}</span>
          <button @click="visualizeGrids(name)" class="option-button">格网</button>
          <button @click="editGrids(name)" class="option-button">修改</button>
          <button @click="deleteArea(name)" class="option-button">删除</button>
        </div>
      </div>

      <!-- 区域命名弹窗 -->
      <div v-if="showNamingDialog" class="modal-overlay">
        <div class="modal-content">
          <h4>为区域命名</h4>
          <input
              v-model="newAreaName"
              placeholder="请输入区域名称"
              class="name-input"
              @keyup.enter="saveArea"
          >
          <div class="modal-buttons">
            <button @click="saveArea" class="confirm-button">确定</button>
            <button @click="cancelNaming" class="cancel-button">取消</button>
          </div>
          <div v-if="nameError" class="error-message">{{ nameError }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import h3tools from '../utils/h3tools.js'
export default {
  name: 'LeftPanel',
  inject: ['mapInstance'],
  data() {
    return {
      isCollapsed: false, // 是否折叠面板
      isDrawing: false,
      polygonAreas: {}, // 存储所有区域 {name: coordinates}
      showNamingDialog: false,
      newAreaName: '',
      nameError: '',
      currentCoordinates: [], // 临时存储当前正在绘制的区域坐标
      pendingPolygonName: '', // 临时存储待命名多边形的名称
      currentMoreOptions: null // 当前显示更多选项的区域名称
    };
  },
  methods: {
    // 面板折叠切换
    togglePanel() {
      this.isCollapsed = !this.isCollapsed;
    },
    // 开始绘制按钮点击事件
    startDrawing() {
      this.isDrawing = true;
      this.currentCoordinates = [];
      // 通知地图组件开始绘制
      this.$parent.$refs.mapRef.startPolygonDrawing();
    },
    // 停止绘制按钮点击事件
    stopDrawing() {
      this.isDrawing = false;
      // 通知地图组件停止绘制
      this.$parent.$refs.mapRef.stopPolygonDrawing();
    },
    // 接收来自地图的坐标数据
    setCoordinates(coords) {
      // 确保 coords 是数组
      if (Array.isArray(coords)) {
        // 处理每个坐标点
        this.currentCoordinates = coords.map(coord => {
          // 如果 coord 是对象，提取 x 和 y 值
          if (typeof coord === 'object' && coord !== null) {
            return [coord.x, coord.y];
          }
          // 如果 coord 是数组，直接使用
          if (Array.isArray(coord)) {
            return coord;
          }
          // 其他情况返回空数组
          return [];
        });
        // 生成临时多边形名称
        this.pendingPolygonName = 'pending_' + Date.now();
        // 绘制完成后弹出命名窗口
        this.showNamingDialog = true;
        this.newAreaName = '';
        this.nameError = '';
      } else {
        // 如果不是数组，设置为空数组
        this.currentCoordinates = [];
      }
    },
    // 保存区域
    saveArea() {
      // 检查名称是否为空
      if (!this.newAreaName.trim()) {
        this.nameError = '区域名称不能为空';
        return;
      }
      // 检查名称是否重复
      if (this.polygonAreas[this.newAreaName]) {
        this.nameError = '区域名称已存在，请输入其他名称';
        return;
      }
      // 保存区域
      this.polygonAreas[this.newAreaName] = this.currentCoordinates;
      // 通知父组件和地图组件处理多边形重命名
      this.$emit('renamePolygon', this.pendingPolygonName, this.newAreaName);
      // 关闭对话框
      this.showNamingDialog = false;
      this.newAreaName = '';
      this.currentCoordinates = [];
      this.pendingPolygonName = '';
    },
    // 取消命名
    cancelNaming() {
      this.showNamingDialog = false;
      this.newAreaName = '';
      this.nameError = '';
      this.currentCoordinates = [];
      this.pendingPolygonName = '';
    },
    // 删除区域
    deleteArea(name) {
      // 删除区域
      delete this.polygonAreas[name];
      // 通知父组件删除地图上的多边形
      this.$emit('deletePolygonByName', name);
    },
    // 编辑格网（未实现）
    editGrids(name) {

    },
    // 格网可视化
    visualizeGrids(name) {
      //根据name拿到多边形区域的坐标
      const coordinates = this.polygonAreas[name];
      const h3Indexes = h3tools.coordinatesToIndexes(coordinates);
      this.$emit('visualizeGrids', h3Indexes);
    },
    focusArea(name) {
      // 聚焦到指定区域
      const coordinates = this.polygonAreas[name];
      if (coordinates && coordinates.length > 0) {
        this.$emit('focusPolygonArea', coordinates);
      }
    },
    clearAllAreas() {
      // 清除所有区域
      this.polygonAreas = {};
      // 通知父组件清除所有区域
      this.$emit('clearAllPolygons');
    }
  },
};
</script>


<style scoped>
.left-panel {
  position: absolute;
  left: 0;
  top: 80px; /* 为顶部标题留出空间 */
  width: 350px;
  height: calc(100% - 80px);
  background: rgba(9, 38, 54, 0.8);
  transition: all 0.3s ease;
  z-index: 10;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.3);
  color: white;
}

.left-panel.collapsed {
  width: 30px;
}

.toggle-button {
  position: absolute;
  right: -20px;
  top: 20px;
  width: 20px;
  height: 40px;
  background: rgba(9, 38, 54, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  box-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
  color: white;
  font-weight: bold;
}

.panel-content {
  padding: 20px;
  color: white;
  height: 100%;
  overflow-y: auto;
}

.panel-content h3 {
  margin-bottom: 15px;
  color: #9ad1ff;
  text-align: center;
}

.draw-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.draw-button, .stop-button, .clear-button {
  background: #008cff;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.draw-button:hover:not(:disabled),
.stop-button:hover:not(:disabled),
.clear-button:hover:not(:disabled) {
  background: #0070d0;
}

.draw-button:disabled,
.stop-button:disabled,
.clear-button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.area-list {
  margin-top: 20px;
}

.area-list h4 {
  margin-bottom: 10px;
  color: #9ad1ff;
}

.area-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.area-item:last-child {
  border-bottom: none;
}

.area-name {
  cursor: pointer;
  color: #9ad1ff;
  flex-grow: 1;
}

.area-name:hover {
  text-decoration: underline;
}

.option-button {
  background: #008cff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  margin: 0 3px; /* 添加左右间距 */
}

.option-button:hover {
  background: #0070d0;
}

.option-button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 5px;
  color: black;
  width: 300px;
}

.modal-content h4 {
  margin-top: 0;
  color: #333;
}

.name-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.modal-buttons {
  display: flex;
  justify-content: space-between;
}

.confirm-button, .cancel-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-button {
  background: #28a745;
  color: white;
}

.cancel-button {
  background: #6c757d;
  color: white;
}

.confirm-button:hover {
  background: #218838;
}

.cancel-button:hover {
  background: #5a6268;
}

.error-message {
  color: #dc3545;
  font-size: 14px;
  margin-top: 10px;
}
</style>
